package com.iqilu.ksd.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Vibrator;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.iqilu.ksd.MyApplication;
import com.iqilu.ksd.R;
import com.iqilu.ksd.bean.UserBean;
import com.iqilu.ksd.constant.Api;
import com.iqilu.ksd.constant.Config;
import com.iqilu.ksd.utils.BaseUtils;
import com.iqilu.ksd.utils.EncryptUtils;
import com.jaeger.library.StatusBarUtil;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.chzz.qrcode.core.QRCodeView;
import org.chzz.qrcode.zxing.ZXingView;
import org.json.JSONException;
import org.json.JSONObject;

import okhttp3.Call;
import okhttp3.Request;

/**
 * 二维码扫描
 * https://github.com/xiaoxinxing12/ChzzQRCode-Android
 * Created by Coofee on 2016/7/18.
 */
public class ScanActivity extends BaseActivity implements QRCodeView.Delegate {

    private static final String TAG = "ScanActivity";

    private static final String MATCH_LOGIN = "https://iuser.iqilu.com/auth/scaned/";
    private static final String MATCH_URL_HTTP = "http://";
    private static final String MATCH_URL_HTTPS = "https://";
    private static final String MATCH_URL_WWW = "www.";
    private static final int REQUESTCODE_LOGIN = 100;

    private UserBean user;
    private String scanUrl;
    private String webId;
    private String aesStr;
    private ProgressDialog progressDialog;

    private final static String KEY_IV = "0000000000000000";
    private final static String KEY_AUTH = "c0e9fcff59ecc3b8";

    private ImageView btLeft;
    private TextView tvTitle;
    private TextView tvRight;
    private Button btLogin;
    private ZXingView zxingContainer;
    private RelativeLayout layLogin;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scan);
        StatusBarUtil.setColor(this, ContextCompat.getColor(this, R.color.blue_dark), Config.STATUSBAR_ALPHA);

        btLeft = getView(R.id.bt_left);
        tvTitle = getView(R.id.tv_title);
        setZHTypeface(tvTitle);
        tvRight = getView(R.id.tv_right);
        btLogin = getView(R.id.bt_login);
        layLogin = getView(R.id.lay_login);
        zxingContainer = getView(R.id.zxing_container);
        tvTitle.setText(getString(R.string.me_scan));
        btLeft.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        tvRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        btLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String url = Api.URL_SCAN_LOGIN + "/" + webId + "?__id=" + Uri.encode(aesStr);
                loginThread(url);
            }
        });

        zxingContainer.setDelegate(this);
        zxingContainer.startSpot();

    }

    private void showLogin() {
        btLeft.setVisibility(View.GONE);
        tvTitle.setVisibility(View.GONE);
        tvRight.setText(getString(R.string.close));
        tvRight.setTextColor(Color.parseColor("#FFFFFF"));
        tvRight.setVisibility(View.VISIBLE);
        layLogin.setVisibility(View.VISIBLE);
    }

    private void startAuth() {
        user = ((MyApplication) getApplication()).getUser();
        if (user != null && user.getId() > 0) {
            String timeStamp = "" + System.currentTimeMillis() / 1000;
            String signStr = EncryptUtils.md52("" + user.getId() + timeStamp + KEY_AUTH);
            String encryptStr = "" + user.getId() + "\n" + BaseUtils.getDeviceId(this) + "\n" + timeStamp + "\n" + signStr;
            aesStr = BaseUtils.AESencrypt(encryptStr, KEY_AUTH, KEY_IV);
//            String url = KsdApi.URL_SCAN_LOGIN + "/"+webId+"?__id=" + Uri.encode(aesStr);
            String url = scanUrl + "?__id=" + Uri.encode(aesStr);
            authThread(url);
        } else {
            Toast.makeText(this, R.string.scan_not_login, Toast.LENGTH_SHORT).show();
            startActivityForResult(new Intent(this, LoginActivity.class), REQUESTCODE_LOGIN);
        }
    }

    private void authThread(String url) {
        OkHttpUtils.get().url(url).tag(this).build().execute(new StringCallback() {
            @Override
            public void onBefore(Request request, int id) {
                super.onBefore(request, id);
                progressDialog = ProgressDialog.show(ScanActivity.this, "", getString(R.string.waiting), true, false);
            }

            @Override
            public void onError(Call call, Exception e, int id) {
                progressDialog.dismiss();
                Toast.makeText(ScanActivity.this, R.string.scan_auth_error, Toast.LENGTH_SHORT).show();
                finish();
            }

            @Override
            public void onResponse(String response, int id) {
                Log.i(TAG, "response=" + response);
                progressDialog.dismiss();
                JSONObject jsonObject = null;
                int status = 0;
                try {
                    jsonObject = new JSONObject(response);
                    status = jsonObject.getInt("status");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                if (jsonObject != null && status == 1) {
                    showLogin();
                } else {
                    Toast.makeText(ScanActivity.this, R.string.scan_auth_error, Toast.LENGTH_SHORT).show();
                    finish();
                }
            }
        });
    }

    private void loginThread(String url) {
        OkHttpUtils.get().url(url).tag(this).build().execute(new StringCallback() {
            @Override
            public void onBefore(Request request, int id) {
                super.onBefore(request, id);
                progressDialog = ProgressDialog.show(ScanActivity.this, "", getString(R.string.waiting), true, false);
            }

            @Override
            public void onError(Call call, Exception e, int id) {
                progressDialog.dismiss();
                Toast.makeText(ScanActivity.this, R.string.scan_auth_error, Toast.LENGTH_SHORT).show();
                finish();
            }

            @Override
            public void onResponse(String response, int id) {
                Log.i(TAG, "response=" + response);
                progressDialog.dismiss();
                JSONObject jsonObject = null;
                int status = 0;
                try {
                    jsonObject = new JSONObject(response);
                    status = jsonObject.getInt("status");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                if (jsonObject != null && status == 1) {
                    Toast.makeText(ScanActivity.this, R.string.login_success, Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(ScanActivity.this, R.string.scan_auth_error, Toast.LENGTH_SHORT).show();
                }
                finish();
            }
        });

    }

    @Override
    protected void onStart() {
        super.onStart();
        zxingContainer.startCamera();
    }

    @Override
    protected void onStop() {
        zxingContainer.stopCamera();
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        zxingContainer.onDestroy();
        super.onDestroy();
    }

    private void vibrate() {
        Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
        vibrator.vibrate(200);
    }

    @Override
    public void onScanQRCodeSuccess(String result) {
        vibrate();
        zxingContainer.stopCamera();
        if (!TextUtils.isEmpty(result)) {
            if (result.startsWith(MATCH_LOGIN)) { // 开始身份认证
                scanUrl = result;
                String[] urlArray = result.split("/");
                webId = urlArray[urlArray.length - 1];
                startAuth();
                return;
            } else if (result.startsWith(MATCH_URL_HTTP) || result.startsWith(MATCH_URL_HTTPS) || result.startsWith(MATCH_URL_WWW)) { // URL则打开
                Intent intent = new Intent(this, ADActivity.class);
                intent.putExtra("fromScan", true);
                intent.putExtra("adUrl", result);
                startActivity(intent);
                finish();
                return;
            }
        }
        Toast.makeText(this, R.string.me_unkonwn, Toast.LENGTH_SHORT).show();
        finish();

    }

    @Override
    public void onScanQRCodeOpenCameraError() {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUESTCODE_LOGIN:
                    startAuth();
                    break;
                default:
                    break;
            }
        }
    }
}
